$(function(){
  const form = layui.form
  const token = localStorage.getItem('Atoken')
  if(token === '') {
    layer.msg('请先登录')
  return $('.slinks').html(`<a href="login.html"><i class="fa fa-hand-o-right"></i>&nbsp;登录</a> |
  <a href="reg.html"><i class="fa fa-registered"></i>&nbsp;注册</a>`)
  } else{
    $.ajax({
      method: 'POST',
      url: '/user/getUserInfo',
      success: function(res) {
        // console.log(res);
        const user = res.data.userInfo.username || res.data.userInfo.mobile
        $('.slinks').html(`<a data-index="${user}" data-v-697ed175="" href="#/user" class="router-link-exact-active router-link-active" aria-current="page">
        <i data-v-697ed175="" class="fa fa-user"></i>&nbsp; 您好${ user }，</a>
        <a data-v-697ed175="" class="fa fa-sign-out"></a>
        `)
       $('.user-info .text h3').html(`昵称 ${ user }<span><b>个性宣言</b>:${res.data.userInfo.notes ? res.data.userInfo.notes : '走自己的路，让人说去吧'}</span>`)
      }
    })
    
  }
  
  // 点击退出登录
  $('.slinks').on('click', '.fa', function(){
    location.href = './login.html'
    localStorage.removeItem('token')
  })

   //  初始化富文本编辑器 
   initEditor()

  // 获取分类和标签
  allCateRender()
  function allCateRender() {
    $.ajax({
      method: 'GET',
      url: '/index/index',
      success: function(res) {
        // console.log(res);
        const { data:{allCate, allTag}} = res
        const fenLeiTpl = allCate.map(item => {
          const { catename, id} = item
          return `
          <option value="${id}">${catename}</option>
          `
        }).join('')
        $('.select').html(fenLeiTpl)
        form.render()
        const tagTpl = allTag.map(item => {
          const { id, tagname } = item
          return `
          <label class="label"><input type="checkbox" class="checkbos" data-index="${tagname}"/>${tagname}</label>
          `
        }).join('')
        $('.tag').html(tagTpl)
      }
    })
  }

  $('#file1').on('change', function(){
    const files = $('#file1')[0].files
    if (files.length <= 0) return alert('请上传')
    const fd = new FormData()
    fd.append('avatar', files[0])
    // console.log(files);
    const urlImg = URL.createObjectURL(files[0])
    $('.form-input img').attr('src', urlImg)
    console.log('urlImg', urlImg)
  })

  $('.form-input .btn').on('click',function(){
    $('#file1').click()
  })

  // 点击发布文章
  let status = 2
  $('#pub_form').on('submit',function(e) {
    e.preventDefault()
    // alert(1)
    const fd = new FormData($('#pub_form')[0])
    fd.append('status',status)
    let dataTxt = []
    if($('.checkbos:checked')) {
      for (let i = 0; i < $('.checkbos:checked').length; i++) {
        dataTxt.push($('.checkbos:checked')[i].dataset.index)
      }
    }
    // console.log(dataTxt)
    const srt = dataTxt.join(',')
    // console.log('srt', srt)
    
    const user = $('.slinks a').data('index')
    // console.log('user', user)
    
    const option = $('option').prop('value')
    console.log('option', option)
    fd.append('cateid',option)
    const img = $('.form-input img').attr('src')
    console.log('img', img)
    $.ajax({
      method: 'POST',
      url: '/user/addArticle',
      data: JSON.stringify({
        title: $('.text').val().trim(),
        author: user,
        cateid: option,
        tags: srt,
        pic: img,
        content: tinyMCE.editors[0].getContent(),
        status: status
      }),
      // data: JSON.stringify(fd),
      contentType: 'application/json; charset=utf-8',

      success: function(res) {
        console.log(res);
        if (res.errno != 0) return layer.msg(res.errmsg)
        layer.msg(res.errmsg)
      }
    })
  })
})